import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class RelayServer {
    private static final int PORT = 5000;
    private static ExecutorService pool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("Server is running and waiting for connections...");

        try {
            while (true) {
                Socket clientSocket1 = serverSocket.accept();
                System.out.println("First client connected.");
                Socket clientSocket2 = serverSocket.accept();
                System.out.println("Second client connected.");

                ClientHandler clientHandler1 = new ClientHandler(clientSocket1, clientSocket2);
                ClientHandler clientHandler2 = new ClientHandler(clientSocket2, clientSocket1);

                pool.execute(clientHandler1);
                pool.execute(clientHandler2);
            }
        } finally {
            serverSocket.close();
        }
    }

    static class ClientHandler implements Runnable {
        private Socket clientSocket;
        private Socket otherSocket;

        ClientHandler(Socket socket, Socket otherSocket) {
            this.clientSocket = socket;
            this.otherSocket = otherSocket;
        }

        public void run() {
            try {
                InputStream input = clientSocket.getInputStream();
                OutputStream output = otherSocket.getOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = input.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            } catch (IOException e) {
                System.err.println("Connection Error: " + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
